﻿using System;
using UnityEngine;

/// <summary>
/// 在线奖励
/// </summary>
public class OnlineAwardsComponent : MonoSingleton<OnlineAwardsComponent>
{
    [SerializeField] OnlineAwardsData data = new OnlineAwardsData();
    Action<int> onTimerEnd;
    long id;
    public int[] times;
   
    public void StartTimer(int[] times,Action<int> action)
    {
        if (action == null)
            return;
        
        this.times = times;
        onTimerEnd = action;

        if(OnlineAwardsData.HasKey())
        {
            data = OnlineAwardsData.Load();
        }
        else
        {
            data.states = new OnlineAwardsState[times.Length];
            data.Save();
        }
        if (TimeHelper.IsSameDay(data.dateTime))
        {
            data.Initialize(this.times);
            data.Save();
            id = TimeTaskComponent.AddTask(data.currentTime, OnTask);
        }
        else
        {
            if (IsEndTimer())
                return;
            
            id = TimeTaskComponent.AddTask(data.currentTime, OnTask);
        }
    }

    /// <summary>
    /// 领取奖励
    /// </summary>
    /// <param name="index">第几个奖励</param>
    /// <returns>是否领取成功</returns>
    public bool GetAwards(int index)
    {
        if(data.states[index] == OnlineAwardsState.Receive)
        {
            data.states[index] = OnlineAwardsState.AlreadyReceive;
            return true;
        }
        return false;
    }

    public OnlineAwardsState GetState(int index)
    {
        if (index >= this.times.Length)
            return OnlineAwardsState.None;
        return data.states[index];
    }

    public int GetTime()
    {
        return (int)(data.currentTime - TimeTaskComponent.GetTime(id));
    }

    public int GetIndex()
    {
        return data.index;
    }

    private void OnDestroy()
    {
        if (IsEndTimer())
            return;

        data.currentTime -= TimeTaskComponent.GetTime(id);
        data.Save();
    }

    void OnTask()
    {
        data.states[data.index] = OnlineAwardsState.Receive;
        data.Save();
        onTimerEnd.Invoke(data.index);
        data.index++;
        data.Save();

        if (IsEndTimer())
            return;

        data.currentTime = this.times[data.index];
        data.Save();
        id = TimeTaskComponent.AddTask(data.currentTime, OnTask);
    }

    bool IsEndTimer()
    {
        return data.index >= this.times.Length;
    }
}
